const {
	getTime,
} = require('../../dateUtils')
const {
	getModuleTree,
} = require('./utils')

const _cmsMongo = global._cmsMongo

module.exports = {

	/**
	 * 添加角色
	 * @param  {[type]} params [description]
	 * @return {[type]}        [description]
	 */
	roleAdd: async function(params) {
		let {
			role_id,
			role_name,
		} = params
		let roleCol = await _cmsMongo.getCollection('role')
		let role = await roleCol.findOne({
			role_id,
		})
		if (role && role._id)
			return -1
		role = await roleCol.findOne({
			role_name,
		})
		if (role && role._id)
			return -2
		params.create_time = getTime()
		params.modify_time = getTime()
		return roleCol.insertOne(params)
	},

	/**
	 * 角色修改
	 * @param  {[type]} params [description]
	 * @return {[type]}        [description]
	 */
	roleModify: async function(params) {
		let {
			role_id,
			role_name,
			desc,
		} = params
		let roleCol = await _cmsMongo.getCollection('role')
		return roleCol.findOneAndUpdate({
			role_id
		}, {
			$set: {
				role_name,
				desc,
				modify_time: getTime(),
			}
		})
	},

	/**
	 * 角色删除
	 * @param  {[type]} params [description]
	 * @return {[type]}        [description]
	 */
	roleDel: async function(params) {
		let role_id = params.role_id
		let roleCol = await _cmsMongo.getCollection('role')
		if (role_id == 'admin')
			return false
		return roleCol.deleteOne({
			role_id,
		})
	},

	getRole(params) {
		// return getRole(params)
	},

	getRoleList: async function(params) {
		let roleCol = await _cmsMongo.getCollection('role')
		let rows = await roleCol.find().toArray()
		return {
			total: rows.length,
			rows,
		}
	},

	funcs: async function(params) {
		let {
			role_id,
		} = params
		let menuMap = {
			menuTree: [],
			moduleFuncMap: {},
		}
		let roleCol = await _cmsMongo.getCollection('role')
		let funcCol = await _cmsMongo.getCollection('func')
		let funcList = await funcCol.find({}, {
			create_time: 0,
			modify_time: 0,
		}).toArray()
		for (let i = 0; i < funcList.length; i++) {
			let func = funcList[i]
			menuMap.moduleFuncMap[func.module_id] = menuMap.moduleFuncMap[func.module_id] || {}
			menuMap.moduleFuncMap[func.module_id][func.func_id] = func
		}
		menuMap.menuTree = await getModuleTree()
		let info = await roleCol.findOne({
			role_id,
		})
		menuMap.func_ids = info && info.func_ids || []
		return menuMap
	},

	grantFuncs: async function(params) {
		let {
			role_id,
			func_ids,
		} = params
		let roleCol = await _cmsMongo.getCollection('role')
		return roleCol.findOneAndUpdate({
			role_id,
		}, {
			$set: {
				func_ids,
				modify_time: getTime(),
			}
		})
	},
}